package com.ipt.frm.pw;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginServlet
 */
public final class LoginServlet extends ServletBase {
	private static final long serialVersionUID = 1L;

	// Parametros inicio del servlet
	static final String INIT_PARAM_USER_NAME = "username";
	static final String INIT_PARAM_USER_PASS = "userpass";
	// parametros de inicio del login.jsp
	static final String LOGIN_JSP_PARAM_USER_NAME = "user";
	static final String LOGIN_JSP_PARAM_USER_PASS = "password";

	static final String MSG = "MSG";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();

	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init(config);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// recoger los valores de la request
		HttpSession session = request.getSession();
		String loginUser = request.getParameter("user");
		String loginPass = request.getParameter("password");
		RequestDispatcher dispatcher = null;

		// recoger los parametros inicio servlet

		// compararlos

		if (getInitParameter(INIT_PARAM_USER_NAME).equals(loginUser)
				&& getInitParameter(INIT_PARAM_USER_PASS).equals(loginPass)) {
			// si validado guardar en session +index.jsp
			session.setAttribute(INIT_PARAM_USER_NAME, loginUser);
			session.setAttribute(INIT_PARAM_USER_PASS, loginPass);

			dispatcher = request.getRequestDispatcher("/index.jsp");
		} else {
			// TODO Meter estos literales en un fichero properties
			Mensaje mensaje = new Mensaje(Tipo.ERROR,
					propertiesMsg.getProperty("servlet.login.invalid"));
			// request.setAttribute("MSG", new Mensaje(Tipo.ERROR,
			// "prueba error"));
			request.setAttribute("MSG", mensaje);

			dispatcher = request.getRequestDispatcher("/login.jsp");

		}

		// si no validado login.jsp + mseg error
		dispatcher.forward(request, response);
	}

}
